package com.chouren.goandroid.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.View;

/**
 * some useful methods for andrid application
 * @author TangLong
 * @date 2014年8月12日
 */
public class AppUtil {
	/**
	 * 获取屏幕宽/高(像素-px)
	 * width:int[0],height:int[1]
	 */
	public static int[] getScreenWidthAndHeight(Activity activity) {
		DisplayMetrics dm = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(dm);  
		int[] wh = new int[2];
		wh[0] = dm.widthPixels;
		wh[1] = dm.heightPixels;
		return wh;
	}
	
	/**
	 * 获取屏幕密度（像素比例：0.75/1.0/1.5/2.0）
	 */
	public static float getScreenDensity(Activity activity) {
		DisplayMetrics dm = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(dm);  
		return dm.density;
	}
	
	/**
	 * 屏幕密度（每寸像素：120/160/240/320）
	 */
	public static int getScreenDensityDpi(Activity activity) {
		DisplayMetrics dm = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(dm);  
		return dm.densityDpi;
	}
	
	/**
	 * 根据手机屏幕将dp大小转换为px大小
	 */
	public static int dip2px(Context context, float dip) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dip * scale + 0.5f);
	}

	/**
	 * 根据手机屏幕将px大小转换为dp大小
	 */
	public static int px2dip(Context context, float px) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (px / scale + 0.5f);
	}
	
	/**
	 * 获取视图控件在屏幕中的坐标
	 * @return width:int[0],height:int[1]
	 */
	public static int[] getViewLocationOnScreen(View view) {
		int[] location = new int[2];  
        view.getLocationOnScreen(location);  
        return location;
	}

	/**
	 * 得到状态栏的高度
	 */
	public static int getStatusHeight(Activity activity) {
		int statusHeight = 0;
		Rect localRect = new Rect();
		activity.getWindow().getDecorView()
				.getWindowVisibleDisplayFrame(localRect);
		statusHeight = localRect.top;

		if (statusHeight == 0) {
			Class<?> localClass;
			try {
				localClass = Class.forName("com.android.internal.R$dimen");
				Object localObject = localClass.newInstance();
				int i5 = Integer.parseInt(localClass
						.getField("status_bar_height").get(localObject)
						.toString());
				statusHeight = activity.getResources()
						.getDimensionPixelSize(i5);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return statusHeight;
	}
}
